<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="toggleDialog" :class="{ active: visible }">
      <span class="placeholder" v-if="!fullLocation">{{placeholder}}</span>
      <span class="value" v-else>{{ fullLocation }}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-if="visible">
      <div v-if="loading" class="loading"></div>

      <template v-else>
        <span @click="changeItem(item)" class="ellipsis" v-for="item in currList" :key="item.id">{{
          item.name
        }}</span>
      </template>
    </div>
  </div>
</template>

<script>
</script>

<script setup>
import { ref, computed, reactive } from 'vue'
import { onClickOutside } from '@vueuse/core'
import axios from 'axios'
export default {
  name: 'XtxCity',
  props: {
    fullLocation: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择默认地址'
    }
  }
}

const emit = defineEmits(['change'])

// 所有省市区数据
const allCityData = ref([])
// 正在加载数据
const loading = ref(false)
// 显示隐藏
const visible = ref(false)
// 打开关闭函数
const open = () => {
  visible.value = true
  loading.value = true
  getCityData().then((data) => {
    allCityData.value = data
    loading.value = false
  })
  // 清空之前选择
  for (const key in changeResult) {
    changeResult[key] = ''
  }
}
const close = () => {
  visible.value = false
}

const toggleDialog = () => {
  visible.value ? close() : open()
}

// 实现点击组件外面关闭
const target = ref(null)
onClickOutside(target, () => {
  // 参数1监听元素
  // 参数二 点击该元素外的其他地方
  close()
})

// 获取省市区
const getCityData = () => {
  // https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json
  // 1,当本地没有缓存，发送请求

  // 2当本地有缓存，取出数据
  // 返回promise在then获取数据
  return new Promise((resolve, reject) => {
    // 约定数据存储在window上cityDate
    if (window.cityData) {
      resolve(window.cityData)
    } else {
      const url =
        'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
      axios.get(url).then((res) => {
        // 缓存
        window.cityData = res.data
        resolve(res.data)
      })
    }
  })
}
// 获取当前显示的地区数组
const currList = computed(() => {
  // 默认省
  let currList = allCityData.value
  // 可能市
  if (changeResult.provinceCode) {
    currList = currList.find(p => p.code === changeResult.provinceCode).areaList
  }
  // 可能区
  if (changeResult.cityCode) {
    currList = currList.find(c => c.code === changeResult.cityCode).areaList
  }
  return currList
})

// 定义选择的数据
const changeResult = reactive({
  provinceCode: '',
  provinceName: '',
  cityCode: '',
  cityName: '',
  countyCode: '',
  countyName: '',
  fullLocation: ''
})

const changeItem = (item) => {
  if (item.level == 0) {
    // 省
    changeResult.provinceCode = item.code
    changeResult.provinceName = item.name
  }
  if (item.level == 1) {
    // 市
    changeResult.cityCode = item.code
    changeResult.cityName = item.name
  }
  if (item.level == 2) {
    // 区
    changeResult.countyCode = item.code
    changeResult.countyName = item.name
    // 最后一集
    // 关闭对话框通知父组件数据
    close()
    changeResult.fullLocation = `${changeResult.provinceName}${changeResult.cityName}${changeResult.countyName}`
    emit('change', changeResult)
  }
}

</script>

<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    // 省略...
    .loading {
      height: 290px;
      width: 100%;
      background: url(../../assets/images/load.gif) no-repeat center;
    }
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>
